from django.db import models

# Create your models here.
from django.urls import reverse
from django.utils.text import slugify
from django_extensions.db.fields import CreationDateTimeField, ModificationDateTimeField
from model_utils import Choices
from model_utils.models import StatusModel
from ckeditor.fields import RichTextField
from ckeditor_uploader.fields import RichTextUploadingField


class DateTimeModel(models.Model):
    class Meta:
        abstract = True

    created = CreationDateTimeField()
    updated = ModificationDateTimeField()


class BaseModel(DateTimeModel, StatusModel):
    class Meta:
        abstract = True

    STATUS = Choices('published', 'draft')

    seo_title = models.CharField(max_length=255, blank=True)
    seo_keywords = models.CharField(max_length=255, blank=True)
    seo_description = models.CharField(max_length=255, blank=True)


class Category(BaseModel):
    name = models.CharField(max_length=255)
    slug = models.CharField(max_length=255, unique=True)

    def __str__(self):
        return self.name

    def get_absulote_url(self):
        return reverse('article_list', args=[self.slug])


class Article(BaseModel):
    name = models.CharField(max_length=255)
    slug = models.SlugField(allow_unicode=True, null=True, blank=True, max_length=250)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    content = RichTextUploadingField()
    view = models.IntegerField(default=5042)

    def __str__(self):
        return self.name

    def save(self, force_insert=False, force_update=False, using=None,
             update_fields=None):
        self.slug = slugify(self.name, allow_unicode=True)
        super(Article, self).save(force_insert=False, force_update=False, using=None,
                                  update_fields=None)

    def add_views(self):
        self.view += 1
        self.save(update_fields=['views'])

    def get_absulote_url(self):
        return reverse('article_detail', args=[self.id])

    def get_mip_absulote_url(self):
        return reverse('article_mip_detail', args=[self.id])
